package cn.shengongying.api.config;

import cn.shengongying.anon.Ignore;
import cn.shengongying.anon.TryGet;
import cn.shengongying.bean.BaseUser;
import cn.shengongying.bean.ResponseResult;
import cn.shengongying.enums.ResponseCodeEnum;
import cn.shengongying.exception.TokenExpireException;
import cn.shengongying.exception.TokenWrongException;
import cn.shengongying.utils.JwtUtils;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Writer;
import java.lang.annotation.Annotation;
import java.nio.charset.StandardCharsets;

/**
 * @author : RXK
 * Date : 2021-7-24 18:02
 * Code Less Think More
 * Desc:
 */
@Configuration
public class WebInterceptor implements HandlerInterceptor {

    private static final Logger LOGGER = LoggerFactory.getLogger(WebInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod method = (HandlerMethod) handler;
            boolean verifyRequest = checkRequest(method, Ignore.class);
            if (!verifyRequest) {
                String token = getToken(request);
                if (StringUtils.isEmpty(token)) {
                    wrongResponse(response, ResponseCodeEnum.login_fail_exception);
                    return false;
                }

                try {
                    BaseUser user = JwtUtils.verifyToken(token);
                    request.setAttribute(JwtUtils.USER,user);
                } catch (TokenExpireException e) {
                    e.printStackTrace();
                    return false;
                } catch (TokenWrongException e) {
                    wrongResponse(response, ResponseCodeEnum.token_fail_exception);
                    return false;
                }
            }

            /*尝试获取当前登录的用户*/
            boolean checkRequest = checkRequest(method, TryGet.class);
            if (checkRequest) {
                String token = getToken(request);
                if (StringUtils.isNotEmpty(token)) {
                    try {
                        BaseUser user = JwtUtils.verifyToken(token);
                        request.setAttribute(JwtUtils.USER,user);
                    } catch (TokenExpireException | TokenWrongException e) {
                        return true;
                    }

                }
            }
        }
        return true;
    }

    private void wrongResponse(HttpServletResponse response, ResponseCodeEnum responseCodeEnum) {
        response.setContentType(MimeTypeUtils.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding(StandardCharsets.UTF_8.displayName());
        ResponseResult<Object> result = ResponseResult.fail(responseCodeEnum);
        try (Writer printWriter = response.getWriter()) {
            printWriter.write(JSON.toJSONString(result));
            printWriter.flush();
        } catch (IOException e) {
            LOGGER.error("返回内容出现异常:",e);
        }
    }

    private String getToken(HttpServletRequest request) {
        return request.getHeader(HttpHeaders.AUTHORIZATION);
    }

    private boolean checkRequest(HandlerMethod method, Class<? extends Annotation> eClass) {
        boolean result = method.hasMethodAnnotation(eClass);
        if (!result) {
            Class<? extends HandlerMethod> aClass = method.getClass();
            result = aClass.isAnnotationPresent(eClass);
        }
        return result;
    }
}
